<?php
/*i
*/

require_once "DBs.php";
require_once "Stone.php";

class DBCrud extends Stone{

	var $myId;
	var $db;
	var $descr;

	function DBCrud($db, $myId, $descr)
	{
		$this->Stone($db);
		$this->myId = $myId;
		$this->descr = $descr;
	}

	function doBasicActions($settings=array())
	{	
		$d = $_POST;

		if (isset($_POST["action_{$this->myId}_add"]))
		{ 		
			//creat insert array based on description
			$inserArr = array();
			foreach($this->descr as $e)
			{
				$value = $d[$e['Field']];
				if ($e['Key'] == 'PRI')
				//we have a primary key
				{
					if ($e['Extra'] == 'auto_increment')
					//if auto increment we set it Null
					{
						$value = Null;
					}
				}
				$insertArr[] = $value;
			}

			DBs::insertRow($this->db, $this->myId, $insertArr);
		
			$line = DBs::selectRow($this->db, $this->myId, 'MAX(id) as maxId');
			$id = $line['maxId'];
						
			$this->_addMsg('Zapis je bil dodan.', 'ok'); //TODO: make it so this strings can be customized ... make them in array that can be preset in code
			return $id;
		}
		else if (isset($_POST["action_{$this->myId}_change"]))
		//change
		{
			$id = $d['id'];			
			unset($d['id']);
			unset($d["action_{$this->myId}_change"]);

			DBs::updateRows($this->db, $this->myId,
				$d, "id = $id"
			);
			$this->_addMsg('Zapis je bil spremenjen.', 'ok');
            return $id;
		}
		else if (isset($_GET["action_{$this->myId}_delete"]))
		//delete
		{
			$id = $_GET["action_{$this->myId}_delete"];
			DBs::deleteRows($this->db, $this->myId, "id = $id");
			$this->_addMsg('Zapis je bil izbrisan', 'ok');
		}
	}
	
}

?>